<script setup lang="ts">
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
import { useSystemStore } from '@/store/system'
import { useUserStore } from '@/store/user'

function checkToken() {
  // 无token时，跳转登录页
  if (!useUserStore().accessToken) {
    let pathname = ''
    // #ifdef H5
    pathname = window.location.pathname
    // #endif
    if (!pathname.startsWith('/example') && pathname !== '/pages/login/index') {
      uni.reLaunch({
        url: '/pages/login/index'
      })
    }
  }
}
// h5端刷新，手动输入网站都会触发 onLaunch
onLaunch(() => {
  checkToken()
  // 监听网络状态
  uni.getNetworkType({ // 第一次进来获取初始网络状态
    success: (res) => {
      useSystemStore().isnetwork = res.networkType !== 'none'
    }
  })
  uni.onNetworkStatusChange(res => { // 监听网络状态变动
    useSystemStore().isnetwork = res.isConnected
  })
})
onShow(() => {
  checkToken()
})
onHide(() => {
  console.log('App Hide')
})
</script>
